//
//  CLOAuthViewController.swift
//  weibo001
//
//  Created by CL on 16/7/10.
//  Copyright © 2016年 CL. All rights reserved.
//

import UIKit

import SVProgressHUD

import AFNetworking

//微博appKey
 let WeiboAppKey = "1182785320"

//微博appsecret
  let WeiboAppSecret = "1606843f6c67acf9cd0771db17fc1ac2"
//微博授权回调页
  let WeiboRedirect_Uri = "http://www.baidu.com"

class CLOAuthViewController: UIViewController {
    
      //MARK   --懒加载控件
    private lazy var webView: UIWebView = UIWebView()

    override func loadView() {
        //自定义视图
       // webView.delegate = self
        view = webView
        
    }
    
    
    

    override func viewDidLoad() {
        super.viewDidLoad()

      view.backgroundColor =  UIColor.whiteColor()
        
        requestOAuthLogin()
    }

  
    private func requestOAuthLogin() {
        //请求地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        //准备请求对象
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
    webView.loadRequest(request)
    }
    
    private func setupNavUI() {
      navigationItem.title = "微博登录"
       navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
   }
  //MARK   --点击事件
    @objc private func  cancelAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    @objc private func  autoFillAction() {
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'hao123guohaibin@163.com'; document.getElementById('passwd').value = 'guohaibin012'")
        
    }
   
    //通过授权码(code)获取accesstoken
    
    private func requestAccesstoken(code: String) {
        
       CLNetworkTools.sharedTools.requestAccesstoken(code) { (response, error) -> () in
        
        if error != nil {
            print(error)
            return
        }
        //代码执行到此,成功回调
        guard let dic = response as? [String :AnyObject] else {
            print("不是个正确的json格式")
            return
        }
        //代码赋值给模型
        let userAccount = CLUserAccount(dic:dic)
        
     
        }
      
        
        
    }
 
}
